<script  lang="ts">
import { defineComponent, reactive, toRefs, ref } from "vue";
import { FormInstance } from "element-plus";
import { LoginData } from '@/type/login';
import {loginByStudentId} from "@/request/api"
import { useRouter } from "vue-router";

export default defineComponent({
  setup() {
    //实例化数据
    const data = reactive(new LoginData());
    const router = useRouter(); // 获取路由
    const rules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { min: 13, max: 13, message: '学号长度为13位', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度为6~18位', trigger: 'blur' }
      ]
    };

    // 登录
    const ruleFormRef = ref<FormInstance>();


    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      // 对表单的内容进行验证
      formEl.validate((valid) => {
        if (valid) {
          loginByStudentId(data.ruleForm).then((res) => {
            console.log(res.data);
            console.log(res.data.data.authentication)
            localStorage.setItem("authentication", res.data.data.authentication);
            // 跳转页面，首页
            router.push('/');
          });
        } else {
          console.log("error submit!");
        }
      });
    };

    // 重置
    const resetForm = () => {
      data.ruleForm.studentId = "";
      data.ruleForm.password = "";
    };

    return { ...toRefs(data), rules, resetForm, ruleFormRef, submitForm }; // 解构对象

  }
})


</script>

<template>
  <div class="login-box">
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
    >
      <h2>材料收集系统</h2>
      <el-form-item label="学号：" prop="studentId">
        <el-input v-model="ruleForm.studentId" autocomplete="off" />
      </el-form-item>

      <el-form-item label="密码：" prop="password">
        <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>

      <el-form-item>
        <el-button class="loginBtn" type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>

        <el-button class="loginBtn" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>




<style scoped lang="scss">
.login-box {
  width: 100%;
  height: 100%;
  background: url("../assets/img.png");
  background-size:cover;
  padding: 1px;
  text-align: center;

  .demo-ruleForm {
    width: 500px;
    margin-top: 300px;
    margin-left: 550px;
    background-color: #fafafa;
    padding: 40px;
    border-radius: 20px; // 圆角
  }

  .loginBtn {
    width: 48%;
  }

  h2 {
    margin-bottom: 20px;
  }
}
</style>